import {extend, RequestOptionsInit} from 'umi-request';
import {history, RequestConfig} from 'umi'

import {message} from "antd";



const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  405: '请求方法不被允许。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};


/**
 * 异常处理程序
 */
const errorHandler = (error: any) => {
  console.info ( "errorHandler", error )
  const {response, data} = error;
  console.log ( response, data )
  if (response && response?.status) {
    const errorText = codeMessage[response?.status] || response?.statusText;

    message.error ( errorText );
  }

  if (!response && !data) {
    message.error ( '哇哦，服务器出错啦，请稍候再试~' );
  } else if (data) {
    message.error ( data?.ret?.msg );
  }
};

// 请求拦截
const authHeaderInterceptor = (url: string, options: RequestOptionsInit) => {
  // const authHeader = { Authorization: 'Bearer xxxxxx' };// 配置统一token使用
  // 判断是否有 token
  const token = localStorage.getItem ( 'token' );
  if (token) {
    return {
      url,
      options: {
        ...options,
        interceptors: true,
        headers: {
          ...options.headers,
          Authorization: `Bearer ${token}`,
        },
      },
    };
  }
  return {url, options};
};
// 响应后拦截
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const demoResponseInterceptors = async (response: Response, options: RequestOptionsInit) => {
  var response1 = response.clone ();
  // response1.json()
//   let {body} = response
  response1.json ().then ( res => {

    console.log (new Date(),response.url, res );

    if (res.status == 406) {
      localStorage.removeItem ( "token" )
      const {query} = history.location;
      const {redirect} = query as {
        redirect: string;
      };
      history.push ( redirect || '/user/login' );
    }
    return res;
  } )
  return response;
};
//
// function getToken() {
//   return localStorage.getItem('token') || '';
// }

export const request: RequestConfig = {
  prefix: `/api1`, // process.env.NODE_ENV === "production" ? '' :'',  // 监测开发环境


  requestInterceptors: [authHeaderInterceptor],
  responseInterceptors: [demoResponseInterceptors],

};

function createClient(baseUrl: string) {
  const request = extend ( {
    prefix: baseUrl,
    errorHandler,
  } );


  // request拦截器, 改变url 或 options.
  request.interceptors.request.use ( (url, options) => {
    let token = localStorage.getItem ( 'token' );
    if (null === token) {
      token = '';
    }
    const version = '1.0.0';
    const lang = "zh-CN";
    const authHeader = {
      Authorization: `${token}`,
      Version: version,
      MyLanguage: `${lang}`,
      'Content-Type': 'application/json',
      Accept: 'application/json',
      terminal: 1
    };
    return {
      url: url,
      options: {...options, interceptors: true, headers: authHeader},
    };
  } );

  request.interceptors.response.use ( demoResponseInterceptors )

  return request;

}

export const drivingRequest = createClient ( '/api/driving/' );
export const oauthRequest = createClient ( '/api/oauth/' );
export const cdnRequest = createClient ( '/api/cdn/' );
export const goodsRequest = createClient ( '/api/goods/' );
export const userRequest = createClient ( '/api/users/' );
export const advertisingRequest = createClient ( '/api/advertisingManagement/' );
export const agentRequest = createClient ( '/api/agent/' );
export const posterRequest = createClient ( '/api/poster/' );
export const orderRequest = createClient ( '/api/order/' );
export const cloudOrderRequest = createClient ( '/api/cloud/order/' );
export const stasticaRequest = createClient ( '/api/stastica/' );
export const couponRequest = createClient ( '/api/coupon/' );
export const taocanRequest = createClient ( '/api/taocan/' );
export const messagesRequest = createClient ( '/api/messages/' );
export const videoRequest = createClient ( '/api/video/' );
export const apiRequest = createClient ( '/api/' );
export const baseRequest = createClient ( '/' );
